package com.zjw.forum.interceptor;

import com.zjw.forum.common.ResultCode;
import com.zjw.forum.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
//    @Value("${forum.login.url}")
//    private String loginUrl;
    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return true 不拦截 </br> false 拦截
     * @throws Exception
     */
    //获取请求之前执行（请求预处理）
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断令牌是否合法
        String user_token = request.getHeader("user_token");
        if(user_token.equals("null")){
//            if(!loginUrl.startsWith("/")){
//                loginUrl+="/";
//            }
//            response.sendRedirect(loginUrl);
            response.setStatus(401);
            return false;
        }
        Claims claims=JWTUtil.verify(user_token);
        if(claims==null){
            log.error(ResultCode.FAILED_TOKEN.getMessage());
//            if(!loginUrl.startsWith("/")){
//                loginUrl+="/";
//            }
//          response.sendRedirect(loginUrl);
            response.setStatus(401);
            return false;
        }
        return true;
    }

}
